package com.myssm.basedao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author Jack Tang
 * @description
 * @create 2023-05-16 22:24
 */
public class ConnUtil {
    public static final String DRIVER = "com.mysql.cj.jdbc.Driver" ;
    public static final String URL = "jdbc:mysql://localhost:3306/fruits?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&&rewriteBatchedStatements=true";
    public static final String USER = "root";
    public static final String PWD = "hyx520";

    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    private static Connection GreateConn(){
        try {
            // 1.加载驱动
            Class.forName(DRIVER);
            // 2.通过驱动管理器获取连接对象
            return DriverManager.getConnection(URL,USER,PWD);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static Connection getConn(){
        // 获取conn
        Connection conn = threadLocal.get();

        if (conn == null){
            conn = GreateConn();
            threadLocal.set(conn);
        }
        return threadLocal.get();
    }

    public static void closeConn() throws SQLException{
        Connection conn = threadLocal.get();
        if (conn == null) {
            return;
        }
        if (!conn.isClosed()) {
            conn.close();
            //threadLocal.set(null);
            threadLocal.remove();
        }
    }
}